import type { FormInstance } from 'element-plus'
import type { ApiResponse, DialogConfig, FormData, SecurityItem } from '~/types/user'
export const useSecurityForm = (refresh: () => Promise<void>) => {
  const formRef = ref<FormInstance>()
  const submitting = ref(false)
  const dialogVisible = ref(false)
  const countdown = ref(0)

  const formData = reactive<FormData>({
    alipayPhone: '',
    phone: "",
    code: '',
    realName: '',
    idCard: '',
    nickname: '',
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
    steamId: '',
    apiKey: '',
    tradeUrl: '',
    steamUsername: '',
    steamPassword: '',
    steamGuardCode: '',
  })
  const button = ref<SecurityItem>({
    title: '',
    label: '',
    button: '',
    action: '',
    showStatus: false,
    verified: false
  })
  const formRules = computed(() => createFormRules(formData))

  const dialogConfig = reactive<DialogConfig>({
    title: '',
    type: ''
  })

  const handleSecurityAction = (item: SecurityItem) => {
    if (item.action === 'Bindsteam') {
      ElMessageBox.confirm(
        '请确保您已在Steam上激活Steam API密钥，否则可能会导致绑定失败。是否继续？',
        '绑定提醒',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        button.value = item
        dialogConfig.type = item.action
        dialogConfig.title = item.action === 'viewIdentity' ? '实名信息' : item.button
        dialogVisible.value = true
      })
      return
    }
    button.value = item
    dialogConfig.type = item.action
    dialogConfig.title = item.action === 'viewIdentity' ? '实名信息' : item.button
    dialogVisible.value = true
  }

  const handleViewIdentity = (item: SecurityItem) => {
    dialogConfig.type = 'viewIdentity'
    dialogConfig.title = '实名信息'
    dialogVisible.value = true
  }

  const handleActionSubmit = async (): Promise<ApiResponse> => {
    switch (dialogConfig.type) {
      case 'phone':
        return await customFetch('/api/user/bindPhone', {
          method: 'POST',
          body: { userPhone: formData.phone },
          isLoading: false
        })
      case 'identity':
        return await customFetch('/api/user/bindIdCard', {
          method: 'POST',
          body: {
            realName: formData.realName,
            idCard: formData.idCard,
          },
          isLoading: false
        })
      case 'password':
        return await customFetch('/api/user/updatePassword', {
          method: 'POST',
          body: {
            userPasswd: formData.newPassword,
            cardNo: formData.oldPassword,
          },
          isLoading: false
        })
      case 'alipay':
        return await customFetch('/api/user/bindAlipayPhone', {
          method: 'POST',
          body: { alipayPhone: formData.alipayPhone },
          isLoading: false
        })

      case 'Bindsteam':
        // 判断是否为解绑操作
        if (button.value.button === '一键解绑') {
          return await customFetch('/api/user/unbindSteam', {
            method: 'POST',
            isLoading: false
          })
        }
        // 绑定操作
        // 绑定操作前的确认提示
        try {
          // 用户确认后继续绑定操作
          return await customFetch('/api/steam/binding', {
            method: 'POST',
            body: {
              steamAccount: formData.steamUsername,
              steamPassword: formData.steamPassword,
              steamToken: formData.steamGuardCode,
            },
          })
        } catch {
          // 用户取消操作
          return { success: false, data: null, message: '用户取消操作' }
        }
      default:
        return { success: false, data: null, message: '未知操作' }
    }
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      submitting.value = true
      const response = await handleActionSubmit()
      if (response.data === 'success') {
        ElMessage.success('操作成功')
        await refresh()
        dialogVisible.value = false
      } else {
        ElMessage.error(response.data || '操作失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('操作失败')
    } finally {
      submitting.value = false
    }
  }

  const handleDialogClose = () => {
    formRef.value?.resetFields()
    Object.keys(formData).forEach(key => {
      formData[key as keyof typeof formData] = ''
    })
  }

  const sendVerificationCode = async () => {
    if (!formData.phone) {
      ElMessage.warning('请先输入手机号码')
      return
    }

    try {
      const response = await customFetch<ApiResponse>('/api/user/sendCode', {
        method: 'POST',
        body: { phone: formData.phone },
        isLoading: false
      })

      if (response.success) {
        countdown.value = 60
        const timer = setInterval(() => {
          countdown.value--
          if (countdown.value <= 0) {
            clearInterval(timer)
          }
        }, 1000)
        ElMessage.success('验证码已发送')
      } else {
        ElMessage.error(response.message || '验证码发送失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('验证码发送失败')
    }
  }

  return {
    formRef,
    formData,
    formRules,
    dialogConfig,
    dialogVisible,
    submitting,
    countdown,
    handleSecurityAction,
    handleViewIdentity,
    handleSubmit,
    handleDialogClose,
    sendVerificationCode
  }
}